
import pymysql

from setting.mysql_setting import *

class ConnectMysql:

    def __enter__(self):
        
        return self

    def __exit__(self,*exc_info):

        if exc_info:

            self.conn.rollback()

        self.close()

    def __init__(self):

        self.conn = pymysql.connect(
            host = HOST,
            port = PORT,
            user = USER,
            password = PASSWORD,
            db = DB,
            charset = CHARSET,
        )

        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

        self.LID_SQL = 'SELECT LAST_INSERT_ID()'

    def close(self):
        '''关闭链接'''

        self.cursor.close()

        self.conn.close()

    def select_all(self, sql, args=None):
        '''查询所有'''

        if args == None:

            self.cursor.execute(sql)
        
        else:

            self.cursor.execute(sql, args)

        result_info = self.cursor.fetchall()

        return result_info

    def select_one(self, sql, args=None):
        '''查询单个'''
    
        if args == None:

            self.cursor.execute(sql)
        
        else:

            self.cursor.execute(sql, args)

        result_info = self.cursor.fetchone()

        # print(result_info)

        return result_info

    def insert_info(self, sql, args=None):
        '''插入数据库'''
        if args == None:

            self.cursor.execute(sql)
        
        else:

            self.cursor.execute(sql, args)
  
        ID = self.select_one(self.LID_SQL)['LAST_INSERT_ID()']#返回结果{'id':1},如果表没有id字段会出问题

        self.conn.commit()

        return ID

    def update_info(self, sql, args=None):
        '''更新'''

        if args == None:
    
            self.cursor.execute(sql)

        else:
    
            self.cursor.execute(sql, args)

        self.conn.commit()

        return {'message': 'ok'}

    def delete_info(self, sql, args=None):
        '''删'''

        if args == None:
    
            self.cursor.execute(sql)

        else:
    
            self.cursor.execute(sql, args)

        self.conn.commit()

        return {'message': 'ok'}